package abel.wlmr.model;

import abel.util.HexString;
import io.netty.buffer.ByteBuf;

public abstract class WlmrUserData {

    private final short guessedLength;

    protected short finalLen = -1;

    /**
     * 
     */
    public WlmrUserData() {
        this((short) -1);
    }

    public WlmrUserData(short guessedLen) {
        this.guessedLength = guessedLen;
    }

    /**
     * @return the dataLength
     */
    public short getGuessedLength() {
        if (guessedLength < 0) {
            throw new IllegalArgumentException("This data part is not for demarshalling");
        }

        return guessedLength;
    }

    /**
     * Default body always reads all bytes into a {@link HexString} object.
     */
    public int checkBuffer(ByteBuf buf) throws WlmrException {
        if (buf.readableBytes() < getGuessedLength()) {
            return -1;
        }
        if (getGuessedLength() < getMinLength()) {
            throw new WlmrException("not enough bytes for " + getClass());
        }

        return 0;
    }

    public abstract int getMinLength();

    /**
     * @return the finalLen
     */
    public abstract short getFinalLen();

    public abstract ByteBuf appendBuf(ByteBuf buf);

    /**
     * Parses the <code>buf</code> by this data unit body or entire part.
     * Returns the parsed bytes length - not readable bytes in the buffer.
     * 
     * @param buf
     * @return
     * @throws WlmrException
     */
    public abstract int parseBuf(ByteBuf buf) throws WlmrException;
}
